import { Select, SelectProps } from "antd";
import { FC, useCallback, useEffect, useState } from "react";
import lodash from "lodash";
import { getCacheDictionary } from "@/utils";

interface DictionarySelectProps {
    value?: string;
    onChange?: (value: string) => void;
}
const DictionarySelect: FC<DictionarySelectProps> = props => {
    const [data, setData] = useState<SelectProps["options"]>([]);
    const [value, setValue] = useState<string>();
    const handleChange = (newValue: string) => {
        setValue(newValue);
        props.onChange?.(newValue);
    };

    const handleSearch = useCallback(
        lodash.debounce(async (title?: string) => {
            const data = await getCacheDictionary();
            setData(data.filter(item => item.title.includes(title || "")).map(item => ({ value: item.key, text: item.title })));
        }, 300),
        []
    );

    useEffect(() => {
        setValue(props.value);
        getCacheDictionary().then(data => {
            setData(data.map(item => ({ value: item.key, text: item.title })));
        });
    }, [props.value]);
    return (
        <Select
            showSearch
            allowClear
            value={value}
            placeholder="请选择字典"
            defaultActiveFirstOption={false}
            suffixIcon={null}
            filterOption={false}
            onSearch={handleSearch}
            onChange={handleChange}
            notFoundContent={null}
            options={(data || []).map(d => ({
                value: d.value,
                label: d.text,
            }))}
        />
    );
};

export default DictionarySelect;
